package com.plan.service.card.impl;

import com.plan.base.constant.BaseCode;
import com.plan.base.entity.Result;
import com.plan.controller.card.request.ExchangeLogPageListReq;
import com.plan.controller.card.request.ExchangeReq;
import com.plan.controller.card.response.ExchangeLogListRes;
import com.plan.controller.user.response.UserVO;
import com.plan.dao.mapper.card.PointProductMapper;
import com.plan.dao.service.card.CardDaoService;
import com.plan.dao.service.card.ExchangeDaoService;
import com.plan.entity.card.Card;
import com.plan.entity.card.ExchangeLog;
import com.plan.entity.card.PointLog;
import com.plan.entity.card.PointProduct;
import com.plan.enums.DelFlagEnum;
import com.plan.enums.PointTypeEnum;
import com.plan.service.card.ExchangeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ExchangeServiceImpl implements ExchangeService {
    @Resource
    private ExchangeDaoService exchangeDaoService;
    @Resource
    private PointProductMapper pointProductMapper;
    @Resource
    private CardDaoService cardDaoService;

    @Override
    public Result<Long> exchange(ExchangeReq req, UserVO user) {
        PointProduct p = pointProductMapper.getOneById(req.getTeamId(), req.getProductId());
        if (p == null) {
            return Result.fail(BaseCode.DATA_NOT_EXIST);
        }
        PointLog pl = new PointLog();
        pl.setTeamId(req.getTeamId());
        pl.setCardId(req.getCardId());
        pl.setPoint(p.getSpendPoint() * -1);
        pl.setEventName("兑换：" + p.getName());
        pl.setPointType(PointTypeEnum.EXCHANGE.getType());
        pl.setDelFlag(DelFlagEnum.NORMAL.getType());

        ExchangeLog exchangeLog = new ExchangeLog();
        exchangeLog.setExchangeName(p.getName());
        exchangeLog.setTeamId(req.getTeamId());
        exchangeLog.setCardId(req.getCardId());
        exchangeLog.setSpendPoint(p.getSpendPoint());
        exchangeLog.setCreatorId(user.getId());
        exchangeLog.setDelFlag(DelFlagEnum.NORMAL.getType());

        Card card = cardDaoService.selectOneById(req.getTeamId(), req.getCardId());
        if (card == null) {
            return Result.fail(BaseCode.DATA_NOT_EXIST);
        }
        if (card.getRemainPoint().compareTo(p.getSpendPoint()) < 0) {
            return Result.fail(BaseCode.POINT_NOT_ENOUGH);
        }
        card.setRemainPoint(card.getRemainPoint() - p.getSpendPoint());

        Long id = exchangeDaoService.exchange(card, exchangeLog, pl);
        return Result.ok(id);
    }

    @Override
    public List<ExchangeLogListRes> getExchangeLogList(ExchangeLogPageListReq req) {
        return exchangeDaoService.getExchangeLogList(req);
    }
}
